package com.bdqn.t313.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * @Description
 * @Autor lzz
 * @Date 2020/11/10 16:55
 */
public class MyBatisUtil {

    private static SqlSessionFactory factory;

    /*
    在静态代码块中构建factory
     */
    static{
        try{
            //获取对mybatis-config.xml的输入流
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            //
            factory = new SqlSessionFactoryBuilder().build(is);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取sqlSession实例
     * @return
     */
    public static SqlSession createSqlSession(){

        return factory.openSession(false);  //false：关闭自动提交开启事务
    }

    /**
     * 关闭sqlSession
     * @param sqlSession
     */
    public static void closeSqlSession(SqlSession sqlSession){
        if(sqlSession!=null){
            //关闭sqlsession
            sqlSession.close();
        }
    }
}
